package com.cch.cooperation.api.blacklist.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cch.cooperation.biz.common.lock.Locker;
import com.cch.cooperation.common.exception.BizException;
import com.cch.cooperation.common.util.SnowflakeIdUtil;
import com.cch.cooperation.dao.blacklist.mapper.BlacklistMapper;
import com.cch.cooperation.dao.blacklist.model.Blacklist;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 黑名单业务处理
 *
 * @author cch
 */
@Service
public class BlacklistServiceImpl {

    @Resource
    private BlacklistMapper mapper;

    @Locker(key = "'LOCK:BLACKLIST:ADD' + #req.userId + #req.targetId")
    public void add(Blacklist req) {
        Blacklist blacklist = get(req.getUserId(), req.getTargetId());
        if (Objects.nonNull(blacklist)) {
            return;
        }
        req.setId(SnowflakeIdUtil.getIdStr());
        req.setTimeCreate(new Date());
        mapper.insert(req);
    }

    public void delete(String userId, String targetId) {
        LambdaQueryWrapper<Blacklist> query = new LambdaQueryWrapper<>();
        query.eq(Blacklist::getUserId, userId);
        query.eq(Blacklist::getTargetId, targetId);
        mapper.delete(query);
    }

    public Blacklist get(String userId, String targetId) {
        if (StrUtil.isEmpty(userId)) {
            throw new BizException("用户id不能为空");
        }
        if (StrUtil.isEmpty(targetId)) {
            throw new BizException("目标id不能为空");
        }
        LambdaQueryWrapper<Blacklist> query = new LambdaQueryWrapper<>();
        query.eq(Blacklist::getUserId, userId);
        query.eq(Blacklist::getTargetId, targetId);
        query.last("limit 1");
        return mapper.selectOne(query);
    }

    public List<Blacklist> queryList(String userId) {
        if (StrUtil.isEmpty(userId)) {
            throw new BizException("用户id不能为空");
        }
        LambdaQueryWrapper<Blacklist> query = new LambdaQueryWrapper<>();
        query.eq(Blacklist::getUserId, userId);
        return mapper.selectList(query);
    }
}
